//
//  AppDelegate.m
//  RootDirectory
//
//  Created by Ryan on 13-2-28.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "AppDelegate.h"
#import "NYMemberCenterDataManager.h"

@implementation AppDelegate

@synthesize startViewController,pannelViewController;

#pragma mark - RootViewController methods

- (StartViewController *)startViewController
{
    if(nil == startViewController)
    {
        startViewController = [[StartViewController alloc] init];
    }
    return startViewController;
}

- (PannelViewController *)pannelViewController
{
    if(nil == pannelViewController)
    {
        pannelViewController = [[PannelViewController alloc] init];
    }
    return pannelViewController;
}

- (void)showPannelViewWithNotification:(NSNotification *)notification
{
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    if([notification.object isEqualToString:@"fromGuide"])
    {
        [self.window addAnimationWithType:kCATransitionPush subtype:kCATransitionFromRight];
    }
    else
    {
        [self.window addAnimationWithType:kCATransitionFade subtype:nil];
    }
    self.window.rootViewController = self.pannelViewController;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [startViewController release];
    [pannelViewController release];
    [_window release];
    [super dealloc];
}

#pragma mark - UIApplicationDelegate methods

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    
    // Optional: automatically send uncaught exceptions to Google Analytics.
    [GAI sharedInstance].trackUncaughtExceptions = YES;
    // Optional: set Google Analytics dispatch interval to e.g. 20 seconds.
    [GAI sharedInstance].dispatchInterval = 20;
    // Optional: set debug to YES for extra debugging information.
    [GAI sharedInstance].debug = NO;
    // Create tracker instance.
    /*id<GAITracker> tracker =*/ [[GAI sharedInstance] trackerWithTrackingId:kGATrackingId];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showPannelViewWithNotification:) name:kShowPannelViewNotification object:nil];
    
    self.window.backgroundColor = [UIColor blackColor];
    self.window.rootViewController = self.startViewController;
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

//- (void)lockApplicationWithPattern
//{
//    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:kPatternSaveOuttimeKey];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//    NSLog(@"set app lock.");
//}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    if([[NYMemberCenterDataManager sharedManager] isLogin])
    {
        //清空用户手势密码保存状态
        NSDictionary *userDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:kIsGestureAuthed];
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:userDict];
        [dict setObject:@"0" forKey:[NYMemberCenterDataManager sharedManager].loginMember.accountId];
        [[NSUserDefaults standardUserDefaults] setObject:dict forKey:kIsGestureAuthed];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:kAsynMenuNotification object:nil];
    }
    [[NYMemberCenterDataManager sharedManager] saveLoginMemberData];
    
    [RYAppBackgroundConfiger clearAllCachesWhenBiggerThanSize:kMaxCacheSize];
    [RYAppBackgroundConfiger preventFilesFromBeingBackedupToiCloudWithSystemVersion:[[UIDevice currentDevice] systemVersion]];
    
    /**
     进入后台后判断是否锁屏
     
    //默认开启锁屏功能，进入后台时设置超时锁屏为no-0，30秒后设置超时锁屏为yes-1
//    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:kPatternSaveOnKey];
    [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:kPatternSaveOuttimeKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if([[[NSUserDefaults standardUserDefaults] valueForKey:kPatternSaveOnKey] isEqualToString:@"1"])
    {
        [self performSelector:@selector(lockApplicationWithPattern) withObject:nil afterDelay:30.f];
    }
    //延长程序进入后台的执行时间
    __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^(void){
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
     **/
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    /**
     回前台超时之后锁定应用
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(lockApplicationWithPattern) object:nil];
    
    if([[[NSUserDefaults standardUserDefaults] valueForKey:kPatternSaveOnKey] isEqualToString:@"1"] &&
       [[[NSUserDefaults standardUserDefaults] valueForKey:kPatternSaveOuttimeKey] isEqualToString:@"1"])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowPatternLockViewNotification object:nil];
    }
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
